var express = require('express');
var config = require('../config');
var Db = require('../database');
var logger = require('../logger');
var utils = require('../utils');
var router = express.Router();

function list(req,res){
    var page = req.body.page || 1;
    var size = req.body.size || 20;
    page = parseInt(page);
    size = parseInt(size);

    var session = req.cookies[config.sessionName];

    if(page < 1 || isNaN(page)){
        page = 1;
    }
    if(size < 10 || isNaN(size)){
        size = 20;
    }
    var start = (page - 1) * size;

    Db.getSession(req,session,function(err,sessionInfo){
        if(err){
            res.json({status:0,error:err.message});
        }else if(parseInt(sessionInfo.right) === 1){
            Db.getConnection(function(err,conn){
                if(err){
                    res.json({status:0,error:err.message});
                }else{
                    var query = {};
                    conn.collection(Db.adminCollection).count(query, function(err,count){
                        if(err){
                            res.json({status:0,error:err.message});
                        }else{
                            if(count < 1){
                                res.json({status:1,error:'',data:{list:[],total:0,page:page}});
                            }else{
                                conn.collection(Db.adminCollection).find(query, {skip:start,limit:size,fields:{password:0},sort:{date:-1}}).toArray(function(err,listInfo){
                                    if(err){
                                        res.json({status:0,error:err.message});
                                    }else{
                                        utils.formatDate(listInfo);
                                        res.json({status:1, error: '',data:{list:listInfo,total:count,page:page}});
                                    }
                                })
                            }
                        }
                    })
                }
            })
        }else{
            res.json({status:0,error:config.ErrorStr.rightNotEnough});
        }
    })
}

function add(req, res){
    var username = req.body.username;
    var password = req.body.password;
    var right = req.body.right || 0;

    if(!username || !password){
        return res.json({status:0,err:config.ErrorStr.missParamErr});
    };

    //logger.info('login param:',username,password);
    Db.getConnection(function(err, conn){
        if(err){
            res.json({status:0,error:err.message});
        }else{
            conn.collection(Db.adminCollection).find({username:username},{fields:{_id:1},limit:1}).toArray(function(err, oldAdminInfo){
                if(err){
                    res.json({status:0,error:err.message});
                }else{
                    if(oldAdminInfo){
                        if(oldAdminInfo.length < 1){
                            var adminObj = {username:username,password:password,right:right,gid:0,date:new Date()};
                            conn.collection(Db.adminCollection).insert(adminObj,function(err, adminInfo){
                                if(err){
                                    res.json({status:0,error:err.err.message});
                                }else{
                                    if(adminInfo && adminInfo.insertedCount == 1){
                                        logger.info(adminInfo)
                                        res.json({status: 1, error: '' ,data:{id:adminInfo.ops[0]._id}});
                                    }else{
                                        res.json({status: 0, error: config.ErrorStr.reqErr});
                                    }
                                }
                            });
                        }else{
                            res.json({status:0,error:config.ErrorStr.accountExistsErr});
                        }
                    }else{
                        res.json({status:0,error:config.ErrorStr.accountNotExistsErr});
                    }
                }
            });
        }
    });
}

function del(req,res){
    var id = req.body.id;
    var session = req.cookies[config.sessionName];
    if(!id){
        res.json({status:0,error:config.ErrorStr.accountNotExistsErr});
    }else{
        Db.getSession(req,session,function(err,sessionInfo){
            if(err){
                res.json({status:0,error:err.message});
            }else if(parseInt(sessionInfo.right) === 1){
                Db.getConnection(function(err,conn){
                    if(err){
                        res.json({status:0,error:err.message})
                    }else{
                        conn.collection(Db.adminCollection).remove({_id:Db.getIdFromStr(id)},function(err,delectInfo){
                            if(err){
                                res.json({status:0,error:err.message});
                            }else{
                                if(delectInfo){
                                    res.json({status:1,error:""});
                                }else{
                                    res.json({status: 0, error: config.ErrorStr.accountNotExistsErr});
                                }
                            }
                        })
                    }
                })
            }else{
                res.json({status:0,error:config.ErrorStr.rightNotEnough});
            }
        })
    }
};

function edit(req,res){
    var id = req.body.id;
    var password = req.body.password;
    var right = req.body.right;
    var session = req.cookies[config.sessionName];

    if(!id || !password || right === undefined){
        res.json({status:0,error:config.ErrorStr.missParamErr});
    }else{
        Db.getSession(req,session,function(err,sessionInfo){
            if(err){
                res.json({status:0,error:err.message});
            }else if(parseInt(sessionInfo.right) === 1){
                Db.getConnection(function(err,conn){
                    if(err){
                        res.json({status:0,err:err.message});
                    }else{
                        conn.collection(Db.adminCollection).update({_id:Db.getIdFromStr(id)},{$set:{password:password,right:right}},function(err,updateInfo){
                            if(err){
                                res.json({status:0,error:err.message});
                            }else{
                                if(updateInfo){
                                    res.json({status:1,error:''});
                                }else{
                                    res.json({status:0,error:config.ErrorStr.accountNotExistsErr});
                                }
                            }
                        });
                    }
                });
            }else{
                res.json({status:0,error:config.ErrorStr.rightNotEnough});
            }
        })
    }
};

function modify(req,res){
    var password = req.body.password;
    var session = req.cookies[config.sessionName];

    if(!password){
        return req.json({status:0,error:config.ErrorStr.missParamErr});
    }else{
        Db.getSession(req,session,function(err,sessionInfo) {
            if (err) {
                res.json({status: 0, error: err.message});
            } else{
                Db.getConnection(function(err,conn){
                    if(err){
                        res.json({status:0,err:err.message});
                    }else{
                        conn.collection(Db.adminCollection).update({_id:sessionInfo.uid},{$set:{password:password}},function(err,updateInfo){
                            if(err){
                                res.json({status:0,error:err.message});
                            }else{
                                if(updateInfo){
                                    res.json({status:1,error:''});
                                }else{
                                    res.json({status:0,error:config.ErrorStr.accountNotExistsErr});
                                }
                            }
                        });
                    }
                });
            }
        })
    }
};

router.post('/list', list);
router.post('/add', add);
router.post('/del', del);
router.post('/edit', edit);
router.post('/modify', modify);

module.exports = router;
